#!/usr/bin/env python3

try:
    from xml.etree.cElementTree import XML
except ImportError:
    from xml.etree.ElementTree import XML
import zipfile
import os
import sys


"""
Module that extract text from MS XML Word document (.docx).
(Inspired by python-docx <https://github.com/mikemaccana/python-docx>)
"""

def get_docx_text(path):
    """
    Take the path of a docx file as argument, return the text in unicode.
    """
    WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    PARA = WORD_NAMESPACE + 'p'
    TEXT = WORD_NAMESPACE + 't'

    document = zipfile.ZipFile(path)
    xml_content = document.read('word/document.xml')
    document.close()
    tree = XML(xml_content)

    paragraphs = []
    for paragraph in tree.iter(PARA):
        texts = [node.text
                 for node in paragraph.iter(TEXT)
                 if node.text]
        if texts:
            paragraphs.append(''.join(texts))

    return '\n\n'.join(paragraphs)


def get_xlsx_text(path):
    SHEET_NAMESPACE = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
    PARA = SHEET_NAMESPACE + 'si'
    TEXT = SHEET_NAMESPACE + 't'
    
    document = zipfile.ZipFile(path)
    xml_content = document.read('xl/sharedStrings.xml')
    document.close()
    tree = XML(xml_content)

    paragraphs = []
    for paragraph in tree.iter(PARA):
        texts = [node.text
                 for node in paragraph.iter(TEXT)
                 if node.text]
        if texts:
            paragraphs.append(''.join(texts))

    return '\n\n'.join(paragraphs)
    
    
def get_pptx_text(path):
    PRESENT_NAMESPACE = '{http://schemas.openxmlformats.org/presentationml/2006/main}'
    DRAWING_NAMESPACE = '{http://schemas.openxmlformats.org/drawingml/2006/main}'
    PARA = DRAWING_NAMESPACE + 'p'
    TEXT = DRAWING_NAMESPACE + 't'
    
    document = zipfile.ZipFile(path)
    paragraphs = []
    
    for f in document.namelist():
        if not f.startswith('ppt/slides/slide'):
            continue

        xml_content = document.read(f)
        tree = XML(xml_content)
        
        for paragraph in tree.iter(PARA):
            texts = [node.text
                 for node in paragraph.iter(TEXT)
                 if node.text]
            if texts:
                paragraphs.append(''.join(texts))

    document.close()

    return '\n\n'.join(paragraphs)


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: {} docx|xlsx|pptx".format(sys.argv[0]))
        sys.exit(0)
    
    file_path = sys.argv[1]
    _, ext = os.path.splitext(file_path)
    
    if ext == ".docx":
        print(get_docx_text(file_path))
    elif ext == ".xlsx":
        print(get_xlsx_text(file_path))
    elif ext == ".pptx":
        print(get_pptx_text(file_path))


